import request from '@/utils/request'
import { createSlice } from '@reduxjs/toolkit'

export const article = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'article',
  // 1. 定义变量(状态数据)
  initialState: {
    channelList: [],
    //-----文章列表--
    articleList: [],
    //------文章分页------
    query: {
      //----文章数据总条数----
      totle: 0,
      //-----当前文章页码-----
      page: 1,
      //------每页数据条数----
      per_page: 10
    }
  },
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    //-----修改频道
    setChannelList (state, action) {
      state.channelList = action.payload
    },
    //------修改文章
    setArticleList (state, action) {
      const { results, ...rest } = action.payload
      state.articleList = results
      state.query = rest
    }
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { setChannelList, setArticleList } = article.actions

// 2. 频道数据
export const getChannelAction = (payload) => {
  return async (dispatch, getState) => {
    const { data } = await request.get('/channels')
    console.log('频道', data.data.channels)
    dispatch(setChannelList(data.data.channels))
  }
}
// 3. 文章列表
export const getArticleAction = (params) => {
  return async (dispatch, getState) => {
    const { data } = await request.get('/mp/articles', {
      params
    })

    console.log('文章列表', data.data)
    dispatch(setArticleList(data.data))

  }
}
export const delArticleAction = (id, params) => {
  return async (dispatch, getState) => {
    const { data } = await request.delete(`/mp/articles/${id}`)

    console.log('删除文章', data)
    // dispatch(getArticleAction(params))

  }
}

// 导出reducer(创建store使用)
export default article.reducer